<template>
	<div class="publicpageview">

		<div class="publitableview">
			<el-button type="primary" size="mini" @click="handleUpdate('',1)">资料录入</el-button>
			<el-button type="primary" size="mini" @click="handleout">导出</el-button>
			<el-table max-height='500px' v-loading="listLoading" :data="list" border fit highlight-current-row size="mini"
				ref="multiTable">

				<el-table-column align="center" label="区房屋管理单位" prop="dname">
				</el-table-column>

				<el-table-column align="center" label="成套" prop="singleuseflag">
				</el-table-column>

				<el-table-column align="center" label="住宅" prop="livingway">
				</el-table-column>

				<el-table-column align="center" label="生效开始时间" prop="taketime">
				</el-table-column>
				<el-table-column align="center" label="分值" prop="score">
				</el-table-column>
				<el-table-column align="center" label="状态">
					<template slot-scope="scope">
						{{scope.row.state==0?'未生效':scope.row.state==1?'已生效':scope.row.state=='已失效'}}
					</template>
				</el-table-column>

				<!-- 
				<el-table-column align="center" label="操作" width="280">
					<template slot-scope="scope">
						<el-button type="text" size="mini" @click="handleUpdate(scope.row,2)">修改</el-button>
						<el-button type="text" size="mini" @click="handleUpdate(scope.row.groupno,3)">详情</el-button>
						<el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
					</template>
				</el-table-column> -->
			</el-table>

			<div class="publicpaginationview">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="listQuery.pageSize" background :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="total" small></el-pagination>
			</div>
		</div>

		<!-- 弹窗部分 -->
		<el-dialog :title="dialogName" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
			<div class="title">{{dialogName}}</div>
			<el-form :rules='rules' :model="addQuery" ref="addForm" class="demo-ruleForm" label-position="right"
				label-width="150px">
				<el-form-item label="区房屋管理单位：" prop="dname">
					<el-select v-if="userDname=='null'" v-model="addQuery.dname" @change='areaChange' value-key="dname">
						<div v-for="(item,index) in areaList" :key="index">
							<el-option :label="item.dname" :value="item" :key="index"></el-option>
						</div>
					</el-select>
					<el-input v-else disabled v-model="addQuery.dname"></el-input>
				</el-form-item>
				<el-form-item label="管理部(分中心)：" prop="aname">
					<el-select v-if="userDname=='null'" v-model="addQuery.aname">
						<div v-for="(item,index) in HouseList" :key="index">
							<el-option :label="item.aname" :value="item.aname" :key="index"></el-option>
						</div>
					</el-select>
					<el-input v-else disabled v-model="addQuery.aname"></el-input>
				</el-form-item>
				<el-form-item label="性质：" prop="livingway">
					<el-select v-model="addQuery.livingway">
						<el-option label="住宅" value="住宅" key="1"></el-option>
						<el-option label="非住宅" value="非住宅" key="0"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-if="addQuery.livingway=='住宅'" label="成套：" prop="singleuseflag">
					<el-select v-model="addQuery.singleuseflag">
						<el-option label="成套" value="成套" key="1"></el-option>
						<el-option label="非成套" value="非成套" key="0"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-if="addQuery.livingway=='非住宅'">
					<el-upload class="upload-demo" drag :action="uploadAction" :file-list="fileList"
						:on-success="handleUploadSuccess" :on-error="handleUploadError" :limit="1" :on-change="handleFileChange"
						:on-remove="handleFileRemove" :before-upload="beforeUpload" multiple>
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>
				<el-form-item label="生效开始时间：" prop="taketime">
					<el-date-picker v-model="addQuery.taketime" type="date" placeholder="选择日期时间" align="right">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="分值：" prop="score">
					<el-input v-model="addQuery.score"></el-input>
				</el-form-item>
			</el-form>

			<div class="saveContent" v-if="type!=3">
				<el-button type="primary" @click="save" size="medium">保 存</el-button>
				<!-- <el-button class="tianjiaButton" v-if="type==1" type="primary" @click="addSuo" size="medium">添加所</el-button> -->
			</div>
			<div class="saveContent" v-if="type==5">
				<el-button type="primary" @click="dialogVisible = false" size="medium">返回</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import dayjs from 'dayjs'
	import * as XLSX from 'xlsx'
	import axios from 'axios';
	import {
		RoomScoreList,
		addRoomScore,
		updRoomScore,
		delRoomScore,
		importNotRoomScoreExcel
	} from '@/api/management'
	import {
		getArea,
		getHouseAdmin
	} from '@/api/industry'
	export default {
		name: 'AccommodationManagementGuanpian',

		data() {
			return {
				listQuery: {
					pageNum: 1,
					pageSize: 20,
				},
				total: 0,
				list: [],
				listLoading: false,
				dialogVisible: false,
				chaifenVisible: false,
				tianjiaVisible: false,
				type: '',
				cfType: '',
				// 区房屋管理单位
				areaList: [],
				// 根据区获取部门
				HouseList: [],
				addQuery: {
					dname: '',
					did: '',
					livingway: '非住宅',
					score: '',
					singleuseflag: '',
					taketime: '',
					aname: '',
					file: ''
				},
				rules: {
					dname: [{
						required: true,
						message: '请选择区房屋管理单位',
						trigger: 'blur'
					}],
					livingway: [{
						required: true,
						message: '请选择性质',
						trigger: 'blur'
					}],
					taketime: [{
						required: true,
						message: '请选择生效开始时间',
						trigger: 'blur'
					}],
					score: [{
						required: true,
						message: '请输入分值',
						trigger: 'blur'
					}],
				},
				tjQuery: {
					remake: '',
					group: '',
					groupnumber: '',
					houseadmin: '',
					status: '',
					did: '',
					aname: '',
					districename: '',
					houseadminname: ''
				},
				GroupNo: '',
				ads: '13',
				hebingList: [],
				newAid: '',
				groupnew: '',
				blockid: '',
				dialogName: '',
				userDname: '',
				uploadAction: 'http://125.39.77.18:9021/mall-admin/fileUpload/upload',
				fileList: [],
				currentFileSrc: []
			}
		},
		watch: {
			'addQuery.livingway': {
				handler(newVal, oldVal) {
					if (newVal == '住宅') {
						this.addQuery.file = ''
					} else if (newVal == '非住宅') {
						this.addQuery.singleuseflag = ''
					}
				}
			}
		},
		computed: {},

		mounted() {
			this.RoomScoreList()
			this.getArea()
			this.userDname = localStorage.getItem('userDname')
		},

		methods: {
			RoomScoreList() {
				let data = {
					pageNum: this.listQuery.pageNum,
					pageSize: this.listQuery.pageSize,
					DID: localStorage.getItem('userDID') == 'null' ? '0' : localStorage.getItem('userDID')
				}
				if (localStorage.getItem('userDname') != 'null') {
					this.addQuery.dname = localStorage.getItem('userDname')
					this.addQuery.did = localStorage.getItem('userDID')
					this.addQuery.aname = localStorage.getItem('userHouseAdminName')
				}
				RoomScoreList(data).then(res => {
					console.log(res)
					this.list = res.data.list
					this.total = res.data.total
				})
			},
			getArea() {
				getArea().then((res) => {
					this.areaList = res.data
				})
			},
			getHouseAdmin(e) {
				getHouseAdmin({
					DID: e
				}).then((res) => {
					this.HouseList = res.data
				})
			},
			// 选择区房屋管理
			areaChange(e) {
				console.log(e)
				this.addQuery.dname = e.dname
				this.addQuery.did = e.did
				this.getHouseAdmin(e.did)
			},
			// 查询
			sumbitCx() {
				this.RoomScoreList()
			},
			// 重置
			resetTop() {},
			// 弹窗保存
			save() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						if (this.dialogName == '租金调整录入') {
							this.addQuery.taketime = dayjs(this.addQuery.taketime).format('YYYY-MM-DD')
							importNotRoomScoreExcel(this.addQuery).then(res => {
								console.log(res)
								this.dialogVisible = false
								this.RoomScoreList()
								this.$message({
									type: 'success',
									message: '操作成功!'
								})
							})
						} else if (this.dialogName == '租金调整修改') {
							this.addQuery.taketime = dayjs(this.addQuery.taketime).format('YYYY-MM-DD')
							updRoomScore(this.addQuery).then(res => {
								console.log(res)
								this.dialogVisible = false
								this.RoomScoreList()
								this.$message({
									type: 'success',
									message: '操作成功!'
								})
							})
						}
						this.popupreset()
					} else {
						console.log('验证失败！')
						return false
					}
				})
			},
			// 重置弹窗
			popupreset() {
				this.addQuery.dname = '',
					this.addQuery.did = '',
					this.addQuery.livingway = '',
					this.addQuery.score = '',
					this.addQuery.singleuseflag = '',
					this.addQuery.taketime = ''
			},
			handleSizeChange(val) {
				this.listQuery.pageNum = 1
				this.listQuery.pageSize = val
				this.RoomScoreList()
			},
			handleCurrentChange(val) {
				this.listQuery.pageNum = val
				this.RoomScoreList()
			},

			handleUpdate(currentData, type) {
				if (type == 1) {
					this.dialogVisible = true
					this.dialogName = '租金调整录入'
				} else if (type == 2) {
					this.dialogVisible = true
					this.dialogName = '租金调整修改'
					let data = JSON.stringify(currentData)
					this.addQuery = JSON.parse(data)
				}
			},
			handleDelete(id) {
				this.$confirm(
						'此操作将删除该条内容，请确认是否继续操作？',
						'删除提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}
					)
					.then(() => {
						let data = {
							id: id
						}
						delRoomScore(data).then((res) => {
							this.RoomScoreList()
							this.$message({
								type: 'success',
								message: '删除成功!'
							})
						})
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						})
					})
			},

			// 调整房屋单位
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then((_) => {
						done()
					})
					.catch((_) => {})
			},

			handleout() {
				this.$confirm('此操作将导出该条内容，请确认是否继续操作？', '导出提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						let data = {
							pageNum: this.listQuery.pageNum,
							pageSize: 999999,
							DID: localStorage.getItem('userDID') == 'null' ? '0' : localStorage.getItem('userDID')
						}
						if (localStorage.getItem('userDname') != 'null') {
							this.addQuery.dname = localStorage.getItem('userDname')
							this.addQuery.did = localStorage.getItem('userDID')
							this.addQuery.aname = localStorage.getItem('userHouseAdminName')
						}
						RoomScoreList(data).then((res) => {
							let list = res.data.list
							let outList = []
							res.data.list.forEach((item, index) => {
								outList.push({
									区房屋管理单位: item.dname,
									成套: item.singleuseflag,
									住宅: item.livingway,
									生效开始时间: item.taketime,
									分值: item.score
								})
							})
							// 获取表格数据
							const data = outList
							// 转换数据为工作表
							const worksheet = XLSX.utils.json_to_sheet(data)
							// 创建新的工作簿
							const workbook = XLSX.utils.book_new()
							// 将工作表添加到工作簿
							XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
							// 导出Excel文件
							XLSX.writeFile(workbook, '租金分值调整.xlsx')
						})
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消导出'
						})
					})
			},
			handleFileChange(file, fileList) {

			},
			// 上传前验证
			beforeUpload(file) {
				const isExcel = file.type === 'application/vnd.ms-excel' ||
					file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
				// if (!isExcel) {
				//     this.$message.error('只能上传 Excel 文件！');
				//     return false; 
				// }

				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isLt2M) {
					this.$message.error('上传文件大小不能超过 2MB!');
					return false;
				}

				return true;
			},
			// 文件选择变化
			handleFileRemove(file, fileList) {
				this.fileList = fileList;
				let arr = [...this.currentFileSrc];
				let i;
				arr.forEach((item, index) => {
					if (item.fileSize == file.size && item.name == file.name) {
						i = index
					}
				})
				arr.splice(i, 1);
				this.currentFileSrc = arr;
				console.log(this.currentFileSrc)

			},
			// 上传成功
			handleUploadSuccess(response, file, fileList) {
				this.fileList = fileList
				if (response.code == 200) {
					this.$message.success('文件上传成功');
					this.currentFileSrc.push(response.data)
					// this.addQuery.file = response.data.url
					 this.fetchMediaFileStream(response.data.url, '文件', 'xls')
					        .then(file => {
					          console.log('文件获取成功:', file);
					          // 在这里处理成功的逻辑，比如将file存入数组或其他操作
					        })
					        .catch(error => {
					          console.error('发生错误:', error.message);
					          // 在这里处理错误，比如提示用户
					        })
				} else {
					this.$message.error('文件上传失败');
					let arr = [...fileList.map(i => i)]
					arr.pop();
					this.fileList = arr;

				}
			},
			// 上传失败
			handleUploadError(err, file) {
				this.$message.error('文件上传失败');
			},
			
			fetchMediaFileStream(mediaUrl, fileName, extension) {
			        return new Promise((resolve, reject) => {
			          const xhr = new XMLHttpRequest();
			 
			          xhr.onload = () => {
			            if (xhr.status === 200) {
			              console.log("打印=", xhr.response);
			              const blob = xhr.response;
			 
			              let mimeType;
			              switch (extension) {
			                case 'mp3':
			                case 'wav':
			                case 'aac':
			                  mimeType = 'audio/*';
			                  break;
			                case 'mp4':
			                case 'avi':
			                case 'mov':
			                  mimeType = 'video/*';
			                  break;
			                case 'jpg':
			                case 'jpeg':
			                case 'png':
			                case 'gif':
			                  mimeType = 'image/*';
			                  break;
			                default:
			                  reject(new Error('未知文件扩展名: ' + extension));
			                  return;
			              }
			 
			              const inferredFileName = fileName;
			              const mediaFile = new File([blob], inferredFileName, {type: mimeType});
			              resolve(mediaFile); // 成功时，解析并返回File对象
			            } else {
			              reject(new Error('请求失败，状态码：' + xhr.status)); // 如果HTTP状态不是200，则拒绝Promise
			            }
			          };
			 
			          xhr.onerror = () => {
			            reject(new Error('网络请求失败，请检查网络连接')); // 处理网络错误
			          };
			 
			          xhr.responseType = 'blob';
			          xhr.open('GET', mediaUrl);
			          xhr.send();
			        });
			      },

		}
	}
</script>
<style scoped>
	.saveContent {
		width: 100%;
		display: flex;
		justify-content: end;
		margin-top: 20px;
		padding-bottom: 20px;
	}

	.saveContents {
		width: 100%;
		display: flex;
		justify-content: space-around;
		margin-top: 20px;
		padding-bottom: 20px;
	}

	.title {
		color: #008c93;
		text-align: center;
		margin-bottom: 20px;
		font-weight: bold;
	}

	.cfguanpian {
		padding-bottom: 20px;
		color: #008c93;
		margin-bottom: 20px;
		font-weight: bold;
	}

	.title2 {
		color: #008c93;
		margin-bottom: 20px;
		font-weight: bold;
	}

	.tianjiaButton {
		border: 2px solid #008c93;
		background-color: #fff;
		color: #008c93;
	}
</style>